<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-card class="filter-container" shadow="never">
      <div class="filter-content">
        <el-form :inline="true" :model="listQuery.params" size="small">
          <el-form-item label="题目内容">
            <el-input v-model="listQuery.params.title" placeholder="请输入题目内容" clearable />
          </el-form-item>

          <el-form-item label="来源类型">
            <el-select v-model="sourceType" placeholder="请选择来源类型" clearable @change="handleSourceChange">
              <el-option label="全部" value=""></el-option>
              <el-option label="在线考试" :value="0"></el-option>
              <el-option label="公共题库" :value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
            <el-button type="success" icon="el-icon-edit" @click="handleStartPractice">开始练习</el-button>
            <el-button v-if="!isHistoryView" type="primary" icon="el-icon-time" @click="handleViewHistory">查看历史错题</el-button>
            <el-button v-if="isHistoryView" type="success" icon="el-icon-back" @click="handleBackToCurrent">返回当前错题</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 练习统计信息 -->
    <el-card v-if="practiceStats" class="stats-container" shadow="never" style="margin-bottom: 20px;">
      <div class="stats-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ practiceStats.currentCount || 0 }}</div>
              <div class="stat-label">当前错题</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ practiceStats.historyCount || 0 }}</div>
              <div class="stat-label">历史错题</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ practiceStats.accuracy ? (practiceStats.accuracy * 100).toFixed(1) : '0.0' }}%</div>
              <div class="stat-label">正确率</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    
    <!-- 统计加载状态 -->
    <el-card v-else class="stats-container" shadow="never" style="margin-bottom: 20px;">
      <div class="stats-content">
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="stat-item">
              <div class="stat-value">
                <i class="el-icon-loading"></i>
                <span style="margin-left: 8px;">正在加载统计数据...</span>
              </div>
              <div class="stat-label">请稍候</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 错题列表 -->
    <el-card class="list-container" shadow="never">
      <data-table
        ref="pagingTable"
        :options="options"
        :list-query="listQuery"
      >
        <template #data-columns>
          <el-table-column label="题目内容" prop="title" min-width="300">
            <template slot-scope="scope">
              <router-link :to="'/qu/view/' + scope.row.quId" class="link-type">
                <span>{{ scope.row.title }}</span>
              </router-link>
            </template>
          </el-table-column>

          <el-table-column label="来源类型" prop="sourceType" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.sourceType === 1 ? 'success' : 'primary'">
                {{ scope.row.sourceType === 1 ? '公共题库' : '在线考试' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="错误次数" prop="wrongCount" width="100" align="center" />

          <el-table-column label="加入时间" prop="createTime" width="180" align="center">
            <template slot-scope="scope">
              {{ scope.row.createTime | parseTime }}
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </template>
      </data-table>
    </el-card>

    <!-- 开始练习对话框 -->
    <el-dialog title="开始练习" :visible.sync="practiceDialogVisible" width="500px">
      <el-form :model="practiceForm" label-width="100px">
        <el-form-item label="练习模式">
          <el-radio-group v-model="practiceForm.orderType">
            <el-radio :label="0">顺序练习</el-radio>
            <el-radio :label="1">乱序练习</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="练习说明">
          <div style="color: #666; font-size: 14px;">
            <p>• 顺序练习：按照错题加入时间从早到晚练习</p>
            <p>• 乱序练习：随机顺序练习错题</p>
            <p>• 当正确次数大于错误次数时，题目将自动归类为历史错题</p>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="practiceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmStartPractice">开始练习</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import DataTable from '@/components/DataTable'
import { parseTime } from '@/utils'
import { pagingBySource, startPractice, getPracticeStats, deleteWrongBook } from '@/api/user/book'
import { post } from '@/utils/request'

export default {
  name: 'WrongBook',
  components: { DataTable },
  filters: {
    parseTime
  },
  data() {
    return {
      sourceType: '',
      practiceStats: null,
      practiceDialogVisible: false,
      practiceForm: {
        orderType: 0
      },
      isHistoryView: false, // 是否查看历史错题
      listQuery: {
        current: 1,
        size: 10,
        params: {
          title: ''
        }
      },
      options: {
        // 列表请求URL
        listUrl: '/exam/api/user/wrong-book/paging'
      }
    }
  },
  created() {
    this.fetchData()
    this.loadPracticeStats()
  },
  activated() {
    // 当页面被激活时（从练习页面返回时）刷新数据
    this.loadPracticeStats()
  },
  mounted() {
    // 监听练习统计刷新事件
    this.$bus && this.$bus.$on('refreshPracticeStats', () => {
      this.loadPracticeStats()
    })
  },
  beforeDestroy() {
    // 清理事件监听
    this.$bus && this.$bus.$off('refreshPracticeStats')
  },
  methods: {
    fetchData() {
      // 初始化数据
    },
    loadPracticeStats() {
      // 加载练习统计信息
      console.log('开始加载练习统计...')
      getPracticeStats({ examId: 'default' }).then(response => {
        console.log('练习统计API响应:', response)
        if (response && response.code === 0) {
          this.practiceStats = response.data
          console.log('练习统计已更新:', response.data)
          console.log('当前错题数:', response.data.currentCount)
          console.log('历史错题数:', response.data.historyCount)
          console.log('正确率:', response.data.accuracy)
          
          // 如果统计数据异常，尝试重新获取
          if (!response.data || response.data.currentCount === undefined) {
            console.warn('统计数据异常，尝试从列表获取...')
            this.loadStatsFromList()
          }
        } else {
          console.error('练习统计响应错误:', response)
          this.loadStatsFromList()
        }
      }).catch(error => {
        console.error('加载练习统计失败:', error)
        // 如果统计加载失败，尝试从错题列表获取数量
        this.loadStatsFromList()
      })
    },
    
    loadStatsFromList() {
      // 从错题列表获取统计信息作为备用方案
      console.log('从错题列表获取统计信息...')
      post('/exam/api/user/wrong-book/paging', {
        current: 1,
        size: 1,
        params: {}
      }).then(response => {
        console.log('错题列表API响应:', response)
        if (response && response.code === 0 && response.data) {
          const totalCount = response.data.total || 0
          this.practiceStats = {
            currentCount: totalCount,
            historyCount: 0,
            totalCorrectCount: 0,
            accuracy: 0
          }
          console.log('从列表获取的统计数据:', this.practiceStats)
        } else {
          console.error('错题列表响应错误:', response)
          // 如果连列表都获取失败，设置默认值
          this.practiceStats = {
            currentCount: 0,
            historyCount: 0,
            totalCorrectCount: 0,
            accuracy: 0
          }
        }
      }).catch(error => {
        console.error('从列表获取统计失败:', error)
        // 设置默认值
        this.practiceStats = {
          currentCount: 0,
          historyCount: 0,
          totalCorrectCount: 0,
          accuracy: 0
        }
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      if (this.isHistoryView) {
        // 历史错题视图
        this.loadHistoryData()
      } else if (this.sourceType !== '') {
        // 如果选择了来源类型，使用特定的接口
        const params = {
          current: this.listQuery.current,
          size: this.listQuery.size,
          params: this.listQuery.params
        }
        pagingBySource(params, parseInt(this.sourceType)).then(response => {
          this.$refs.pagingTable.setData(response.data)
        })
      } else {
        // 使用默认接口（当前错题）
        this.$refs.pagingTable.options.listUrl = '/exam/api/user/wrong-book/paging'
        this.$refs.pagingTable.getList()
      }
    },
    resetFilter() {
      this.listQuery.params = {
        title: ''
      }
      this.sourceType = ''
      this.isHistoryView = false // 重置时返回当前错题视图
      this.handleFilter()
    },
    handleSourceChange() {
      // 来源类型改变时触发搜索
      this.handleFilter()
    },
    handleView(row) {
      // 查看题目详情
      this.$router.push({ path: '/qu/view/' + row.quId })
    },
    handleDelete(row) {
      // 删除错题
      this.$confirm('确定要从错题本中删除该题目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        deleteWrongBook([row.id]).then(response => {
          if (response && response.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 刷新列表和统计数据
            this.handleFilter()
            this.loadPracticeStats()
          } else {
            this.$message({
              type: 'error',
              message: response.msg || '删除失败，请稍后重试'
            })
          }
        }).catch(error => {
          console.error('删除错题失败:', error)
          this.$message({
            type: 'error',
            message: '删除失败，请稍后重试'
          })
        })
      })
    },
    handleStartPractice() {
      this.practiceDialogVisible = true
    },
    handleViewHistory() {
      // 切换到历史错题视图
      this.isHistoryView = true
      this.loadHistoryData()
    },
    loadHistoryData() {
      // 加载历史错题数据
      post('/exam/api/user/wrong-book/paging-history', {
        current: 1,
        size: 10,
        params: {}
      }).then(response => {
        if (response && response.code === 0 && response.data) {
          this.$refs.pagingTable.setData(response.data)
        } else {
          this.$message.warning('暂无历史错题')
        }
      }).catch(error => {
        console.error('加载历史错题失败:', error)
        this.$message.error('加载历史错题失败，请稍后重试')
      })
    },
    handleBackToCurrent() {
      // 返回当前错题视图
      this.isHistoryView = false
      this.handleFilter()
    },
    confirmStartPractice() {
      startPractice({
        examId: 'default',
        orderType: this.practiceForm.orderType
      }).then(response => {
        if (response && response.code === 0 && response.data && response.data.id) {
          this.practiceDialogVisible = false
          // 跳转到练习页面
          this.$router.push({
            path: `/wrong-book/practice/${response.data.id}`,
            query: { orderType: this.practiceForm.orderType }
          })
        } else {
          this.$message.warning('没有可练习的错题')
        }
      }).catch(error => {
        console.error('开始练习失败:', error)
        this.$message.error('开始练习失败，请稍后重试')
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.link-type {
  color: #409EFF;
  text-decoration: none;
}

.link-type:hover {
  text-decoration: underline;
}

.stats-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stats-content {
  padding: 10px 0;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}
</style>